import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:untitled1/app/widgets/toast/MyToast.dart';

import '../../../../utils/utilImagePicker.dart';
import 'RefundDialogPageController.dart';
//退单
class RefundDialogPage extends StatefulWidget {
  @override
  _RefundDialogPageState createState() => _RefundDialogPageState();
}

class _RefundDialogPageState extends State<RefundDialogPage> {
  int selectedReasonIndex = -1;
  final List<String> reasons = ['联系不上', '需求无效', '其他原因'];
  final RefundDialogPageController controllerData = Get.put(
    RefundDialogPageController(),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black.withOpacity(0.5),
      resizeToAvoidBottomInset: false, // ✅ 禁止键盘弹出时顶起
      body: SafeArea(
        child: Obx(
          () => Container(
            color: Colors.white,
            width: double.infinity,
            height: double.infinity,
            padding: const EdgeInsets.all(20),
            child: Column(
              children: [
                // 顶部标题栏
                Stack(
                 alignment: Alignment.center,
                  children: [
                    Align(
                      alignment: Alignment.center,
                      child: Text(
                        '确定退单吗？',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: GestureDetector(
                        onTap: () => Navigator.of(context).pop(),
                        child: CircleAvatar(
                          radius: 14,
                          backgroundColor: Colors.grey[300],
                          child: Icon(Icons.close, size: 18, color: Colors.black),
                        ),
                      ),
                    )
                  ],
                ),


                SizedBox(height: 10),

                // ✅ 滚动内容区（退单原因 + 文本框 + 图片）
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 退单原因
                        Text(
                          '退单原因:',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                        SizedBox(height: 10),

                        Row(
                          children: List.generate(reasons.length, (index) {
                            bool isSelected = selectedReasonIndex == index;
                            return GestureDetector(
                              onTap: () {
                                setState(() {
                                  selectedReasonIndex = index;
                                });
                              },
                              child: Container(
                                margin: EdgeInsets.only(right: 12),
                                padding: EdgeInsets.symmetric(
                                  horizontal: 12,
                                  vertical: 6,
                                ),
                                decoration: BoxDecoration(
                                  color:
                                      isSelected
                                          ? Colors.red
                                          : Colors.grey[300],
                                  borderRadius: BorderRadius.circular(3),
                                ),
                                child: Text(
                                  reasons[index],
                                  style: TextStyle(
                                    color:
                                        isSelected
                                            ? Colors.white
                                            : Colors.black,
                                  ),
                                ),
                              ),
                            );
                          }),
                        ),

                        SizedBox(height: 20),

                        // 输入框
                        Center(
                          child: Container(
                            width: MediaQuery.of(context).size.width * 0.8,
                            height: 100,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: TextField(
                              maxLines: null,
                              expands: true,
                              keyboardType: TextInputType.multiline,
                              decoration: InputDecoration.collapsed(
                                hintText: '请输入退单说明...',
                              ),
                            ),
                          ),
                        ),

                        SizedBox(height: 20),

                        // 上传图片标题
                        Text(
                          '上传图片:',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 10),

                        // ✅ GridView 不能滚动 + 自动高度
                        GridView.builder(
                          itemCount: controllerData.imgList.length,
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3,
                                mainAxisSpacing: 10,
                                crossAxisSpacing: 10,
                              ),
                          itemBuilder: (context, index) {
                            return buildItem(index);
                          },
                        ),

                        SizedBox(height: 20), // 底部留空，避免遮挡按钮
                      ],
                    ),
                  ),
                ),

                // ✅ 底部按钮不被键盘顶起
                Container(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 10),
                  child: ElevatedButton(
                    onPressed: () {
                      // 提交逻辑
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                      padding: EdgeInsets.symmetric(vertical: 14),
                    ),
                    child: Text(
                      '提交',
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget buildItem(int index) {
    if (index == controllerData.imgList.length - 1 &&
        '' == controllerData.imgList[index].path) {
      return GestureDetector(
        onTap: () async {
          // 添加图片逻辑
          if (controllerData.imgList.length >= 10) {
            MyToast.showSystemToast("最多9张图片");
            return;
          }
          List<File> files = await utilImagePicker.pickMultiImages();
          if (files.isNotEmpty) {
            controllerData.imgList.insertAll(0, files);
          }
          if (controllerData.imgList.length > 10) {
            List<File> files = controllerData.imgList.sublist(0, 9);
            File file = controllerData.imgList.last;
            controllerData.imgList.clear();
            controllerData.imgList.addAll(files);
            controllerData.imgList.add(file);
          }
        },
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(child: Icon(Icons.add, size: 40, color: Colors.grey)),
        ),
      );
    } else {
      File file = controllerData.imgList[index];
      return GestureDetector(
        onTap: () async {
          // 查看图片逻辑
          // MyToast.showSystemToast("chakna");
        },
        child: Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Image.file(
                file,
                width: 100,
                height: 100,
                fit: BoxFit.cover,
              ),
            ),
           Align(
             alignment: Alignment(0.7, -0.9),
              child:  GestureDetector(
                onTap: (){
                  controllerData.imgList.removeAt(index);
                },
                child: CircleAvatar(
                  radius: 14,
                  backgroundColor: Colors.grey[300],
                  child: Icon(Icons.close, size: 18, color: Colors.black),
                ),
              ),
           ),
          ],
        ),
      );
    }
  }
}
